﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using AirportApp.Data;
using AirportApp.Resources;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace AirportApp
{
    public partial class MainPage : PhoneApplicationPage
    {
        AirportViewModel vm;
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            vm = (AirportViewModel)App.Current.Resources["AirportViewModelDataSource"];
            //vm.Load();

            this.Loaded += (s, e) =>
            {
                this.ApplicationBar.IsVisible = true;

                ApplicationBarIconButton btn = (ApplicationBarIconButton)this.ApplicationBar.Buttons[0];
                btn.Text = Strings.Search;

                // Menuitems
                ApplicationBarMenuItem settingsMenu = (ApplicationBarMenuItem)ApplicationBar.MenuItems[0];
                settingsMenu.Text = Strings.Settings;
                settingsMenu.Click += (s1, e1) =>
                {
                    NavigationService.Navigate(new Uri("/SettingsPage.xaml", UriKind.Relative));
                };

#if DEBUG
                // Add addition Menuitsm
                ApplicationBarMenuItem _clearData = new ApplicationBarMenuItem();
                _clearData.Text = "Clear data";
                _clearData.Click += (s1, e1) =>
                {
                    vm.Clear();
                };
                this.ApplicationBar.MenuItems.Add(_clearData);

                ApplicationBarMenuItem _loadData = new ApplicationBarMenuItem();
                _loadData.Text = "Load Data";
                _loadData.Click += (s1, e1) =>
                {
                    vm.Load();
                };
                this.ApplicationBar.MenuItems.Add(_loadData);
#endif 
            };

            _search.TextChanged += (s, e) =>
            {
                //UpdateSearch();
                if (_timer.IsEnabled)
                {
                    _timer.Stop();
                }
                _timer.Start();
            };

            _timer = new DispatcherTimer();
            _timer.Interval = new System.TimeSpan(0,0,0,0,500);
            _timer.Tick += (s,e) => {
                _timer.Stop();
                UpdateSearch();
            };

            
        }

        private void UpdateSearch()
        {
            string searchText = _search.Text.ToLower();
            switch (_currentSearch)
            {
                case 0:
                    vm.FilterByAirport(searchText);
                    break;

                case 1:
                    vm.FilterByCountry(searchText);
                    break;

                default:
                    break;
            }
        }

        private void _reloadData_Click(object sender, System.EventArgs e)
        {
            vm.Load();
        }

        private void _clearData_Click(object sender, System.EventArgs e)
        {
            vm.Clear();
        }

        int _currentSearch;
        // bool _searchActive = false;

        private bool _searchActive
        {
            get { return _search.Visibility == System.Windows.Visibility.Visible; }
        }

        private void _searchButton_Click(object sender, System.EventArgs e)
        {
            ToggleSearch();
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (_searchActive)
            {
                ToggleSearch();
                e.Cancel = true;
            }
            base.OnBackKeyPress(e);
        }
        private void ToggleSearch()
        {
            if (_searchActive)
            {
                _search.Visibility = System.Windows.Visibility.Collapsed;
                _currentSearch = _panorama.SelectedIndex;
                _panorama.Margin = new System.Windows.Thickness(0, 0, 0, 0);
                _search.Text = string.Empty;
            }
            else
            {
                _search.Visibility = System.Windows.Visibility.Visible;
                _search.Text = string.Empty;
                _currentSearch = _panorama.SelectedIndex;
                _panorama.Margin = new System.Windows.Thickness(0, -158, 0, 0);
            }
        }

        private void _countryList_DoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            ListBox lb = sender as ListBox;
            string country = (string)lb.SelectedItem;

            ToggleSearch();
            _search.Text = country;
            _currentSearch = 0;
            _panorama.DefaultItem = _panorama.Items[0]; 
        }

        DispatcherTimer _timer;
        private LongListSelector currentSelector;

        private void LongListSelector_GroupViewOpened(object sender, GroupViewOpenedEventArgs e)
        {
            //Hold a reference to the active long list selector.
            currentSelector = sender as LongListSelector;

            //Construct and begin a swivel animation to pop in the group view.
            IEasingFunction quadraticEase = new QuadraticEase { EasingMode = EasingMode.EaseOut };
            Storyboard _swivelShow = new Storyboard();
            ItemsControl groupItems = e.ItemsControl;

            foreach (var item in groupItems.Items)
            {
                UIElement container = groupItems.ItemContainerGenerator.ContainerFromItem(item) as UIElement;
                if (container != null)
                {
                    Border content = VisualTreeHelper.GetChild(container, 0) as Border;
                    if (content != null)
                    {
                        DoubleAnimationUsingKeyFrames showAnimation = new DoubleAnimationUsingKeyFrames();

                        EasingDoubleKeyFrame showKeyFrame1 = new EasingDoubleKeyFrame();
                        showKeyFrame1.KeyTime = TimeSpan.FromMilliseconds(0);
                        showKeyFrame1.Value = -60;
                        showKeyFrame1.EasingFunction = quadraticEase;

                        EasingDoubleKeyFrame showKeyFrame2 = new EasingDoubleKeyFrame();
                        showKeyFrame2.KeyTime = TimeSpan.FromMilliseconds(85);
                        showKeyFrame2.Value = 0;
                        showKeyFrame2.EasingFunction = quadraticEase;

                        showAnimation.KeyFrames.Add(showKeyFrame1);
                        showAnimation.KeyFrames.Add(showKeyFrame2);

                        Storyboard.SetTargetProperty(showAnimation, new PropertyPath(PlaneProjection.RotationXProperty));
                        Storyboard.SetTarget(showAnimation, content.Projection);

                        _swivelShow.Children.Add(showAnimation);
                    }
                }
            }

            _swivelShow.Begin();
        }

        private void LongListSelector_GroupViewClosing(object sender, GroupViewClosingEventArgs e)
        {
            //Cancelling automatic closing and scrolling to do it manually.
            e.Cancel = true;
            if (e.SelectedGroup != null)
            {
                currentSelector.ScrollToGroup(e.SelectedGroup);
            }

            //Dispatch the swivel animation for performance on the UI thread.
            Dispatcher.BeginInvoke(() =>
            {
                //Construct and begin a swivel animation to pop out the group view.
                IEasingFunction quadraticEase = new QuadraticEase { EasingMode = EasingMode.EaseOut };
                Storyboard _swivelHide = new Storyboard();
                ItemsControl groupItems = e.ItemsControl;

                foreach (var item in groupItems.Items)
                {
                    UIElement container = groupItems.ItemContainerGenerator.ContainerFromItem(item) as UIElement;
                    if (container != null)
                    {
                        Border content = VisualTreeHelper.GetChild(container, 0) as Border;
                        if (content != null)
                        {
                            DoubleAnimationUsingKeyFrames showAnimation = new DoubleAnimationUsingKeyFrames();

                            EasingDoubleKeyFrame showKeyFrame1 = new EasingDoubleKeyFrame();
                            showKeyFrame1.KeyTime = TimeSpan.FromMilliseconds(0);
                            showKeyFrame1.Value = 0;
                            showKeyFrame1.EasingFunction = quadraticEase;

                            EasingDoubleKeyFrame showKeyFrame2 = new EasingDoubleKeyFrame();
                            showKeyFrame2.KeyTime = TimeSpan.FromMilliseconds(125);
                            showKeyFrame2.Value = 90;
                            showKeyFrame2.EasingFunction = quadraticEase;

                            showAnimation.KeyFrames.Add(showKeyFrame1);
                            showAnimation.KeyFrames.Add(showKeyFrame2);

                            Storyboard.SetTargetProperty(showAnimation, new PropertyPath(PlaneProjection.RotationXProperty));
                            Storyboard.SetTarget(showAnimation, content.Projection);

                            _swivelHide.Children.Add(showAnimation);
                        }
                    }
                }

                _swivelHide.Completed += _swivelHide_Completed;
                _swivelHide.Begin();

            });
        }

        private void _swivelHide_Completed(object sender, EventArgs e)
        {
            //Close group view.
            if (currentSelector != null)
            {
                currentSelector.CloseGroupView();
                currentSelector = null;
            }
        }

    }
}